import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/libs/http'
import state from './state'
import mutations from './mutations'
// import app from './modules/app'
// import user from './modules/user'


import {
    getMenusByRouters,
    getHomeRoute
} from '@/libs/menus'
import routers from '@/router/routers'


Vue.use(Vuex)
export default new Vuex.Store({
    state,
    mutations,

    getters: {
        collapseSidebar: state => state.collapseSidebar,
        menus: (state, getters) => {
            state.homeRoute = getHomeRoute(routers)
            return getMenusByRouters(routers, state.access, state.isAdmin)
        },

        user: state => state.user,
        isAdmin: state => state.isAdmin,
        roles: state => state.roles,
        permissions: state => state.permissions,
        access: state => state.access
    },
    actions: {
        /**
         * 登录
         * @param {*} param0
         * @param {*} data
         */
        async handleLogin({ commit, state }, data) {
            const loginRes = await http({ url: '/system/user/login', method: 'POST', data })

            if (loginRes.status && loginRes.data.token != undefined) {
                commit('SET_TOKEN', loginRes.data.token)

                const userRes = await http({
                    url: '/system/user/getUserInfoByToken',
                    method: 'POST',
                    data: { token: loginRes.data.token }
                })
                if (userRes.status) {
                    commit('SET_USER', userRes.user)
                    commit('SET_IS_ADMIN', userRes.user.superAdmin)
                    commit('SET_ROLES', userRes.roles)
                    commit('SET_ACCESS', userRes.access)
                }
            }
            return loginRes
        },

        /**
         * 退出登录
         * @param {*} param0
         */
        async handleLogout({ dispatch, commit, state }) {
            const res = await http({ url: '/system/user/logout', method: 'GET' })
            if(res.status) {
                dispatch('FedLogOut')
            }
            return res
        },

        /**
         * 前端登出
         * @param {*} param0
         * @param {*} data
         */
        FedLogOut({ commit, state }, data) {
            commit('SET_TOKEN', null)
            commit('SET_USER', null)
            commit('SET_IS_ADMIN', false)
            commit('SET_ROLES', [])
            commit('SET_ACCESS', [])
            sessionStorage.clear()
        }
    }
})
